##parameters=file


file = file.readlines()

headers = file[0]

propertyIds = [h.replace('"','').strip() for h in headers.split(',')[5:]]

regtool = context.portal_registration
grouptool = context.portal_groups

def trimDict( d ):
    """ Removes keys with empty values """
    
    trimmed = {}
        
    for key, value in d.items():
        if value: trimmed[key] = value
                    
    return trimmed
            
def addUserToGroup( username, groupname ):
    
    groupname = groupname.replace("group_","")
    
    user  = context.portal_membership.getMemberById( username )
    group = context.portal_groups.getGroupById( groupname )
    
    group.addMember( user )

for row in file[1:]:
    
    type, username, password, s_roles, s_groups, sPropertyValues = row.split('","',5)
    
    type = type.replace('"','')
    
    roles = s_roles.split('|')
    groups = s_groups.split('|') 
    
    propertyValues = [x.replace('"','').strip() for x in sPropertyValues.split('","')]
    
    
    metadata = dict(zip( propertyIds, propertyValues ))
    
    metadata['username'] = username # Legacy
    
    metadata = trimDict( metadata )
    
    
    if type == 'user':
        
        if not 'email' in metadata: metadata['email'] = "noemail@example.com"
        
        print "Adding USER", username, password, roles
        print metadata
        try:
            regtool.addMember( username, password, roles, '', properties=metadata )
            
            for group in groups:
                addUserToGroup( username, group )
            
        except Exception, e:
            print "Error: %s" % str(e)
            print propertyIds
            print propertyValues
    
    elif type == 'group':
        print "Adding GROUP", username
        grouptool.addGroup( username, roles, groups, **metadata )
    
    

    
return printed    